package com.mrobuy.util;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;

public class ExcelUtils {

    public static void setCellValue(XSSFSheet sheet, int row, int cell, String value) {
        XSSFRow _row = getRow(sheet, row);
        XSSFCell dataCell = getCell(_row, cell);
        dataCell.setCellValue(value);
    }

    public static XSSFRow getRow(XSSFSheet sheet, int row) {
        XSSFRow _row = sheet.getRow(row);
        if ( _row==null ) {
            _row = sheet.createRow(row);
        }
        return _row;
    }

    public static XSSFCell getCell(XSSFRow _row, int col) {
        XSSFCell dataCell = _row.getCell(col);
        if ( dataCell==null ) {
            dataCell = _row.createCell(col);
        }
        return dataCell;
    }


    public static XSSFCellStyle getCellStyle(XSSFSheet sheet, int row, int cell) {
        XSSFRow _row = getRow(sheet, row);
        XSSFCell dataCell = getCell(_row, cell);
        return dataCell.getCellStyle();
    }

    public static void applyCellStyle(XSSFSheet sheet, int row, int cell, XSSFCellStyle cellStyle) {
        XSSFRow _row = getRow(sheet, row);
        XSSFCell dataCell = getCell(_row, cell);
        dataCell.setCellStyle(cellStyle);
    }

    public static void setCellFormula(XSSFSheet sheet, int row, int cell, FormulaFactory factory) {
        XSSFRow _row = getRow(sheet, row);
        XSSFCell dataCell = getCell(_row, cell);
        if ( factory!=null ) {
            dataCell.setCellFormula(factory.build(sheet, row, cell));
        }
    }

    public static interface FormulaFactory {
        String build(XSSFSheet sheet, int row, int cell);
    }
}
